<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------

/**
 * 会员ajax类
 * @package  ajax
 * @subpackage  backend
 * @author   allen.qiang
 */

quanli_require('module/base/customer/quanliCust.class.php');

class ajax_customer {

    public function execute() {

        if (isset($_REQUEST['operFlg']) && $_REQUEST['operFlg'] > 0) {

            switch($_REQUEST['operFlg']) {

                case 1: //查询会员列表
                    $this->searchCustomerList();
                    break;

                case 4: //查询会员信息
                    $this->searchCustomer();
                    break;

                case 10: //会员信息变更日志列表
                    $this->customerLogDetail();
                    break;

                case 13: //会员账户交易历史
                    $this->customerAccountChangeLog();
                    break;

                case 19: //添加/修改会员发票信息
                    $this->editCustInvoice();
                    break;

                case 20: //删除发票信息
                    $this->delCustInvoice();
                    break;

                case 100:
                    //mod by 20141104 allen.qiang FUN-BK-0019-手工重置会员密码 start
                    //if (!isset($_REQUEST['act']) || !in_array($_REQUEST['act'], array('del', 'edit', 'change', 'reset_pwd'))) {
                    if (!isset($_REQUEST['act']) || !in_array($_REQUEST['act'], array('del', 'edit', 'change', 'reset_pwd','reset_pwd1'))) {
                    //mod by 20141104 allen.qiang FUN-BK-0019-手工重置会员密码 end
                        returnJsonData('参数错误');
                    }

                    if ($_REQUEST['act'] == 'edit') {

                        $this->editCust();//新增、修改会员

                    } else if ($_REQUEST['act'] == 'change') {

                        $this->customerStatusChange();//启用、禁用会员

                    } else if ($_REQUEST['act'] == 'reset_pwd') {

                        $this->doRandPasswd();//重置密码

                    } else if ($_REQUEST['act'] == 'reset_pwd1') {
                    //add by 20141104 allen.qiang FUN-BK-0019-手工重置会员密码 start
                        $this->doRandPasswd1();//手工重置会员密码
                    }
                    //add by 20141104 allen.qiang FUN-BK-0019-手工重置会员密码 end

                    break;

                default:
                    returnJsonData('参数错误');
                    break;

            }

        } else {

            returnJsonData('参数错误');

        }

    }

    /**
     * 查询会员信息
     */
    private function searchCustomer() {

        //实例化会员类
        $quanliCust = new quanliCust();

        //查询会员信息
        $customer_array = $quanliCust->searchCustomerDetail( $_REQUEST );

        if ($customer_array) {
            returnJsonData('ok', 200, $customer_array);
        } else {
            returnJsonData('会员信息没有找到', 404);
        }

    }

    /**
     * 删除发票信息
     */
    private function delCustInvoice() {

        if (!isset($_REQUEST['pcustID']) || !is_numeric($_REQUEST['pcustID']))
            die( json_encode( array( 'code' => 406, 'message' => '参数错误' ) ) );

        if (!isset($_REQUEST['id']) || !is_numeric($_REQUEST['id']))
            die( json_encode( array( 'code' => 400, 'message' => '缺少参数' ) ) );

        global $G_PGLOB;


        //实例化会员类
        $customerHandler = new customerHandler( $G_PGLOB->DBCA );

        //删除发票信息
        $result_array = $customerHandler->delCustInvoice($_REQUEST['pcustID'], $_REQUEST['id']);

        echo json_encode( $result_array );

    }


    /**
     * 添加/修改会员发票信息
     */
    private function editCustInvoice() {

        global $G_PGLOB;

        if (!isset($_REQUEST['pcustID']) || !is_numeric($_REQUEST['pcustID']))
            die( json_encode( array( 'code' => 406, 'message' => '参数错误' ) ) );

        //实例化会员类
        $customerHandler = new customerHandler( $G_PGLOB->DBCA );

        //添加/修改会员发票信息
        $_REQUEST['creator'] = $G_PGLOB->currentUserID;
        $result_array = $customerHandler->editCustInvoice( $_REQUEST );

        echo json_encode($result_array);

    }

    /**
     * 查询会员列表
     */
    private function searchCustomerList() {

        global $G_PGLOB;

        //实例会员类
        $quanliCust = new quanliCust();

        //查询会员信息
        $customer_array = $quanliCust->searchCustomerInfo( $_REQUEST );

        //组织返回的数据
        $result_array = array(
            'page' => $_REQUEST['page'],
            'total' => $_REQUEST['count'],
            'rows' => array()
        );

        if ($customer_array) {

            $edit_permission = $G_PGLOB->has_permission(3001);

            foreach($customer_array as &$customer) {

                $recom_custname = '';
                if (quanli_is_int($customer['recom_pcustID'])) {
                    $arg_array = array(
                        'pcustID' =>  $customer['recom_pcustID']
                    );
                    $recom_cust_array = $quanliCust->searchCustomerDetail( $arg_array );
                    if ($recom_cust_array) {
                        $recom_custname = $recom_cust_array['custname'];
                    }
                }


                $pcustID = $customer['pcustID'];
                $custID = $customer['custID'];

                $operate = '';
                if (isset($_REQUEST['act']) && $_REQUEST['act'] == 'callcenter') {
                    $operate .= '<a href="/quanliadmin/app/callcenter/callcenter.pscript?operFlg=2&pcustID=' . $pcustID . '">选择</a>&nbsp;';
                } else {
                    $operate .= '<a href="javascript:void(0);" onclick="customer.edit(' . $pcustID . ')">修改</a>&nbsp;'.
                        '<a href="javascript:void(0);" onclick="customer.customerAccount(' . $pcustID . ')">账户</a>&nbsp;'.
                        '<a href="javascript:void(0);" onclick="customer.customerBill(\'' . $custID . '\')">订单</a>&nbsp;'.
                        '<a href="javascript:void(0);" onclick="customer.customerLog(' . $pcustID . ')">日志</a>&nbsp;'.
                        '<a href="javascript:void(0);" onclick="customer.deliver(' . $pcustID . ')">收货地址</a>&nbsp;'.
                        '<a href="javascript:void(0);" onclick="customer.resetPassWord(' . $pcustID . ', \'' . $custID . '\')">重置密码</a>&nbsp;'.
                        //add by 20141104 allen.qiang FUN-BK-0019-手工重置会员密码 start
                        '<a href="javascript:void(0);" onclick="customer.resetPassWord1(' . $pcustID . ', \'' . $custID . '\')">手工重置</a>';
                        //add by 20141104 allen.qiang FUN-BK-0019-手工重置会员密码 end
                }

                if( $customer['sexy'] == 3 ){
                    $sexy =  "保密";
                }else if( $customer['sexy'] == 1 ){
                    $sexy = "男";
                }else if( $customer['sexy'] == 2 ){
                    $sexy = "女";
                }else{
                    $sexy = "";
                }

                if (isset($_REQUEST['act']) && $_REQUEST['act'] == 'callcenter') {
                    if ($edit_permission) {

                        $result_array['rows'][] = array (
                            'id' => $pcustID,
                            'cell' => array(
                                $operate,
                                $pcustID,
                                $custID,
                                $customer['custname'],
                                $customer['rankName'],
                                $customer['sumAmt'],
                                $customer['custSourceName'],
                                $customer['custType'] == 1 ? '普通会员' : '访客会员',
                                $customer['isMobileVerify'] == 1 ? "是" : "否",
                                $customer['provinceName'],
                                $customer['cityName'],
                                $customer['countyName'],
                                $customer['address'],
                                $customer['email'],
                                $customer['phone'],
                                $customer['mobile'],
                                $sexy,
                                $customer['birthday'],
                                $recom_custname,
                                $customer['createTime']//add by allen.qiang 20150203 注册日期
                            )
                        );

                    } else {
                        $result_array['rows'][] = array(
                            'id' => $pcustID,
                            'cell' => array(
                                $pcustID,
                                $custID,
                                $customer['custname'],
                                $customer['rankName'],
                                $customer['sumAmt'],
                                $customer['custSourceName'],
                                $customer['custType'] == 1 ? '普通会员' : '访客会员',
                                $customer['isMobileVerify'] == 1 ? "是" : "否",
                                $customer['provinceName'],
                                $customer['cityName'],
                                $customer['countyName'],
                                $customer['address'],
                                $customer['email'],
                                $customer['phone'],
                                $customer['mobile'],
                                $sexy,
                                $customer['birthday'],
                                $recom_custname,
                                $customer['createTime']//add by allen.qiang 20150203 注册日期
                            )
                        );
                    }
                }else{
                    if ($edit_permission) {

                        $result_array['rows'][] = array (
                            'id' => $pcustID,
                            'cell' => array(
                                $operate,
                                $customer['useFlg'] == 1 ?
                                    '<a href="javascript: void(0);" onclick="customer.doAction(' . $customer['pcustID'] . ', 0) " >启用</a>' :
                                    '<a href="javascript: void(0);" onclick="customer.doAction(' . $customer['pcustID'] . ', 1 ) " >禁用</a>' ,
                                $pcustID,
                                $custID,
                                $customer['custname'],
                                $customer['rankName'],
                                $customer['sumAmt'],
                                $customer['custSourceName'],
                                $customer['custType'] == 1 ? '普通会员' : '访客会员',
                                $customer['isMobileVerify'] == 1 ? "是" : "否",
                                $customer['provinceName'],
                                $customer['cityName'],
                                $customer['countyName'],
                                $customer['address'],
                                $customer['email'],
                                $customer['phone'],
                                $customer['mobile'],
                                $sexy,
                                $customer['birthday'],
                                $recom_custname,
                                $customer['createTime']//add by allen.qiang 20150203 注册日期
                            )
                        );

                    } else {
                        $result_array['rows'][] = array(
                            'id' => $pcustID,
                            'cell' => array(
                                $pcustID,
                                $custID,
                                $customer['custname'],
                                $customer['rankName'],
                                $customer['sumAmt'],
                                $customer['custSourceName'],
                                $customer['custType'] == 1 ? '普通会员' : '访客会员',
                                $customer['isMobileVerify'] == 1 ? "是" : "否",
                                $customer['provinceName'],
                                $customer['cityName'],
                                $customer['countyName'],
                                $customer['address'],
                                $customer['email'],
                                $customer['phone'],
                                $customer['mobile'],
                                $sexy,
                                $customer['birthday'],
                                $recom_custname,
                                $customer['createTime']//add by allen.qiang 20150203 注册日期
                            )
                        );
                    }
                }

            }
        }

        echo json_encode($result_array);

    }


    /**
     * 新增、修改会员信息
     */
    function editCust() {

        global $G_SHOP;

        //实例会员类
        $quanliCust = new quanliCust();

        //新增、修改会员信息
        $_REQUEST['operator'] = $G_SHOP->currentUserID;
        $result_array = $quanliCust->editCustomer( $_REQUEST );

        if (isset($result_array['data'])) {

            //加载短信类
            quanli_include('module/base/common/quanliSms.class.php');

            //实例化短信类
            $quanliSms = new quanliSms();

            //生成短信内容
            $data_array = array(
                '$pwd' => $result_array['data']['pwd'],
                '$custID' => $result_array['data']['custID'],
                '$mobile' => $result_array['data']['mobile']
            );
            $sms_content = $quanliSms->getSmsContent( 'auth_send_pwd', $data_array );
            if (!$sms_content) {
                returnJsonData('短信初始化失败', 404);
            }

            //发送短信
            $result_array = $quanliSms->sendSMS( $result_array['data']['mobile'], $sms_content );
            if ($result_array['code'] == 200) {
                returnJsonData('会员新增成功，密码已短信通知', 200);
            } else {
                returnJsonData('会员新增成功，但短信发送密码失败', 200);
            }

        } else {
            returnJsonData($result_array['message'], $result_array['code']);
        }

    }

    //会员信息变更日志列表
    function customerLogDetail(){

        global $G_PGLOB;

        //实例化日志操作公共类
        $logHandler = new quanliLog();

        //组装查询数组
        $searchArr = array('logCategoryID'=>9,
            'logItem'=>trim($_REQUEST['logItem']),
            'page'=>$_REQUEST['page'],
            'rp'=>$_REQUEST['rp'],
            'sortname'=>$_REQUEST['sortname'],
            'sortorder'=>$_REQUEST['sortorder']);

        //查询包裹取消/编辑信息
        $result  =  $logHandler->searchLogInfo( $searchArr );

        //组织返回的数据
        $result_array = array(
            'page'  => $_REQUEST['page'],
            'total' => $searchArr['count'],
            'rows'  => array()
        );

        if( $result ){

            foreach ( $result as $key=>$value){

                $result_array['rows'][$key] = array(
                    'id' =>  $value['logItem'],
                    'cell' => array(
                        $value['logItem'],
                        $value['createTime'],
                        $value['creator'],
                        $value['extend_1']
                    )
                );

            }

        }

        echo json_encode($result_array);
        return;

    }


    //会员账户交易历史
    public function customerAccountChangeLog(){

        quanli_require('module/func/eai.func.php');

        if (!isset($_REQUEST['pcustID'], $_REQUEST['subjectID']) || !quanli_is_int($_REQUEST['pcustID']) || !quanli_is_int($_REQUEST['subjectID'])) {
            returnJsonData('参数错误');
        }

        //实例crm类
        $crm_obj = eai_crm();

        //查询会员账户变更记录
        $account_log_array = $crm_obj->searchCustAccountLog($_REQUEST['pcustID'], $_REQUEST['subjectID'], $_REQUEST['page'], $_REQUEST['rp'], $_REQUEST['sortname'], $_REQUEST['sortorder']);

        //组织返回的数据
        $result_array = array(
            'page'  => $_REQUEST['page'],
            'total' => 0,
            'rows'  => array()
        );

        if( $account_log_array ) {

            $result_array['total'] = $account_log_array['count'];

            foreach ( $account_log_array['data'] as &$log) {

                $result_array['rows'][] = array(
                    'id' =>  $log['seqno'],
                    'cell' => array(
                        $log['createTime'],
                        $log['actionTypeName'],
                        $log['changeAccount'],
                        $log['useableAccount'],
                        $log['changeLockAccount'],
                        $log['lockAccount'],
                        $log['externalTranCode'],
                        $log['remark']
                    )
                );

            }

        }

        echo json_encode($result_array);

    }


    //重置会员密码
    function doRandPasswd() {

        if (!isset($_REQUEST['pcustID']) || !quanli_is_int($_REQUEST['pcustID'])) {
            returnJsonData('参数错误');
        }

        global $G_PGLOB;


        //加载短信类
        quanli_include('module/base/common/quanliSms.class.php');

        //实例化短信类
        $quanliSms = new quanliSms();

        $pwd = get_random_string(6); //随机生成的密码

        $mobile = ''; //手机号码

        try {

            $G_PGLOB->DBCA->beginTransaction();

            //获取并更新用户密码
            $customer_obj = new entity('cust_master');
            $customer_obj->pcustID = $_REQUEST['pcustID'];
            if (!$G_PGLOB->DBCA->fetch($customer_obj)){
                throw new Exception('会员信息没有找到', 404);
            }
            $mobile = decryptD($customer_obj->mobile);
            if (empty($mobile) || !is_mobile($mobile)) {
                throw new Exception('会员没有手机号码，无法重置密码');
            }
            $customer_obj->pwd = md5($pwd);
            $G_PGLOB->DBCA->save($customer_obj);

            //日志类
            $logHandler = new quanliLog($G_PGLOB->DBCA);

            $log_array['logItem'] = $_REQUEST['pcustID'];
            $log_array['logCategoryID'] = 9;
            $log_array['operator'] = $G_PGLOB->currentUserID;
            $log_array['extend_1'] = '重置密码';
            $logHandler->saveLogInfo( $log_array );

            $G_PGLOB->DBCA->commit();

        } catch (Exception $e) {

            $G_PGLOB->DBCA->rollBack();

            if ($e->getCode() > 0) {

                returnJsonData($e->getMessage(), $e->getCode());

            } else {

                error_log($e->getMessage());
                returnJsonData('系统错误', 500);

            }
        }

        //生成短信内容
        $data_array = array(
            '$pwd' => $pwd,
            '$custID' => $customer_obj->custID,
            '$mobile' => $mobile,
        );
        $sms_content = $quanliSms->getSmsContent( 'reset_pwd', $data_array );
        if (!$sms_content) {
            returnJsonData('短信初始化失败', 404);
        }

        //发送短信
        $result_array = $quanliSms->sendSMS( $mobile, $sms_content );
        if ($result_array['code'] == 200) {
            returnJsonData('会员密码重置成功，已短信通知', 200);
        } else {
            returnJsonData('会员密码重置成功，但短信通知失败', 200);
        }

    }

    /**
     * 更新会员使用状态
     *
     */
    private function customerStatusChange () {

        //实例会员类
        $quanliCust = new quanliCust();

        //新增、修改会员信息
        $result_array = $quanliCust->changeCustomerUseFlg( $_REQUEST );

        returnJsonData($result_array['message'], $result_array['code']);

    }

    //add by 20141104 allen.qiang FUN-BK-0019-手工重置会员密码 start
    function doRandPasswd1() {

        if (!isset($_REQUEST['pcustID']) || !quanli_is_int($_REQUEST['pcustID'])) {
            returnJsonData('参数错误');
        }
        global $G_PGLOB;

        $pwd_1 = $_REQUEST['pwd_1'];//密码
        $pwd_2 = $_REQUEST['pwd_2'];//确认密码
        if (!is_pwd($pwd_1)) {
            returnJsonData('密码必须是6-30位字符，可使用字母、数字', 400);
        }
        if (!is_pwd($pwd_2)) {
            returnJsonData('密码必须是6-30位字符，可使用字母、数字', 400);
        }
        if($pwd_1!=$pwd_2)
        {
            returnJsonData('两次输入密码不一致', 400);
        }
        try {

            $G_PGLOB->DBCA->beginTransaction();

            //获取并更新用户密码
            $customer_obj = new entity('cust_master');
            $customer_obj->pcustID = $_REQUEST['pcustID'];
            if (!$G_PGLOB->DBCA->fetch($customer_obj)){
                throw new Exception('会员信息没有找到', 404);
            }
            $mobile = decryptD($customer_obj->mobile);
            if (empty($mobile) || !is_mobile($mobile)) {
                throw new Exception('会员没有手机号码，无法重置密码', 404);
            }
            $customer_obj->pwd = md5($pwd_2);
            $G_PGLOB->DBCA->save($customer_obj);

            //日志类
            $logHandler = new quanliLog($G_PGLOB->DBCA);

            $log_array['logItem'] = $_REQUEST['pcustID'];
            $log_array['logCategoryID'] = 9;
            $log_array['operator'] = $G_PGLOB->currentUserID;
            $log_array['extend_1'] = '重置密码';
            $logHandler->saveLogInfo( $log_array );

            $G_PGLOB->DBCA->commit();
            returnJsonData('会员密码重置成功', 200);

        } catch (Exception $e) {

            $G_PGLOB->DBCA->rollBack();

            if ($e->getCode() > 0) {

                returnJsonData($e->getMessage(), $e->getCode());

            } else {

                error_log($e->getMessage());
                returnJsonData('系统错误', 500);

            }
        }

    }
    //add by 20141104 allen.qiang FUN-BK-0019-手工重置会员密码 end
}